package com.xiaobai.monitor;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ThreadOperSharedVariable2 {
    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            //临界区
            for (int i = 0; i < 5000; i++) {
                room.increment();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                room.decrement();
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("count:{}", room.getCount());
    }
}

class Room {
    private int count = 0;
    //这个方法是同步方法，所以是同步的 锁的还是方法的调用者
    //synchronized只能锁的是对象
    //synchronized如果加到的静态的话 那么就会锁住的类对象
    public synchronized void increment() {
        count++;
    }

    public void decrement() {
        synchronized (this) {
            count--;
        }
    }

    public synchronized int getCount() {
        return count;
    }
}
